﻿var ns = namespace("kaskelot.sp.ui");

ns.personsearch = function () {
	var cookieName = "personsearch";

	function init() {
		var c = kaskelot.sp.ui.cookies.getCookie(cookieName);
		if (c != undefined) {
			$("#TypDropDownList").val(c.typId);
			$("#InaktivaCheckbox").prop('checked', c.visaInaktiva);
			$("#FritextTextbox").val(c.fritext);
			$("#PostnummerTextbox").val(c.postnummer);
			$("#PersonnummerTextbox").val(c.personnummer);
			$("#NamnTextbox").val(c.namn);
			$("#UppdragDropDownList").val(c.funktionId);
			$("#BemannadeCheckbox").prop('checked', c.endastBemannade);

			getList();
		}

		$(".chzn-select").chosen();
		$(".chzn-select-deselect").chosen({ allow_single_deselect: true, disable_search: true });

		$("#title-container").html("Sök/lista person");

		$("#search-button").click(
			function () {
				getList();
			}
		);

		$("#clear-button").click(
			function () {
				$("#TypDropDownList").val("");
				$("#InaktivaCheckbox").prop('checked', false);
				$("#FritextTextbox").val("");
				$("#PostnummerTextbox").val("");
				$("#PersonnummerTextbox").val("");
				$("#NamnTextbox").val("");
				$("#UppdragDropDownList").val("");
				$("#BemannadeCheckbox").prop('checked', false);

				$("#TypDropDownList").trigger("liszt:updated");
				$("#UppdragDropDownList").trigger("liszt:updated");
			}
		);

		$("#check-all").click(function () {
			$("#search-results tbody input").prop("checked", $("#check-all").prop("checked"));
		});

		$("#personsearch-content-container").keypress(function (event) {
			if (event.which == 13) {
				kaskelot.sp.ui.personsearch.getList();
			}
		});
	}

	function getSelectedValue(dataTag) {
		var val = [];
		$("#search-results tbody input:checked").each(function (i) {
			val[i] = $(this).attr("data-" + dataTag);
		});

		return val;
	}

	function showEmail() {
		var val = getSelectedValue("email");

		if (val.length == 0) {
			kaskelot.sp.ui.prompts.showErrorPrompt("Du måste först välja de personer du vill skicka epost till.");
			return;
		}

		var selector = "#epost-form";
		kaskelot.sp.ui.formutils.getAndShowPostForm({
			params: {
				formName: "EpostForm",
				idList: val,
			},
			selector: selector,
			openFunction: function () {
				$(".ui-dialog-buttonset .ui-button:first").hide();

				var doc = document;
				var text = doc.getElementById("Text");

				// Sätt text som markerad
				if (doc.body.createTextRange) { // ms
					var range = doc.body.createTextRange();
					range.moveToElementText(text);
					range.select();
				} else if (window.getSelection) { // moz, opera, webkit
					var selection = window.getSelection();
					var range = doc.createRange();
					range.selectNodeContents(text);
					selection.removeAllRanges();
					selection.addRange(range);
				}
			},
			okFunction: function () {
				$(selector).dialog("close");
			}
		});
	}

	function getList() {
		// Parametrar
		var typ = $("#TypDropDownList").val();
		var inaktiva = $("#InaktivaCheckbox").prop('checked');
		var fritext = $("#FritextTextbox").val();
		var postnummer = $("#PostnummerTextbox").val();
		var personnummer = $("#PersonnummerTextbox").val();
		var namn = $("#NamnTextbox").val();
		var funktion = $("#UppdragDropDownList").val();
		var bemannade = $("#BemannadeCheckbox").prop('checked');

		var data = { fritext: fritext, visaInaktiva: inaktiva, typId: typ, postnummer: postnummer, personnummer: personnummer, namn: namn, funktionId: funktion, endastBemannade: bemannade };
		kaskelot.sp.ui.cookies.setCookie(cookieName, data);

		$(".blockable-container").block({ message: '<h1>Var god vänta...</h1>' });

		$.ajax({
			url: L_Menu_BaseUrl + "/_vti_bin/Kaskelot.SP.Resources/ClientPersonService.svc/SearchPersoner",
			type: "GET",
			data: data,
			processData: true,
			cache: false,
			success:
				function (data) {
					if (!data.SearchPersonerResult.HasError) {
						$("#search-results tbody").html(
							$("#search-personer-template").render(data.SearchPersonerResult.Data)
						);
					}

					$("#search-results input").click(function () {
						if ($("#search-results tbody input:checked").length > 0) {
							$("#select-button").removeAttr("disabled");
							$("#utskrift-button").removeAttr("disabled");
						}
						else {
							$("#select-button").attr("disabled", "disabled");
							$("#utskrift-button").attr("disabled", "disabled");
						}
					});

					$(".blockable-container").unblock();
				},
			error:
				function (xhr) {
					$(".blockable-container").unblock();
					kaskelot.sp.ui.prompts.showErrorPrompt("Sökningen misslyckades.");
				}
		});
	}

	function showTemplates() {
		var val = getSelectedValue("id");

		var selector = "#template-form";
		kaskelot.sp.ui.formutils.getAndShowPostForm({
			params: {
				formName: "TemplateForm",
				idList: val
			},
			selector: selector,
			openFunction: function () {
				$(".ui-dialog-buttonset .ui-button:first").hide();
				$("#IdList").val(getSelectedValue("id"));
				$("#person-render").show();
				$("#byggnad-render").hide();
				$("#valdistrikt-render").hide();
			},
			okFunction: function () {
				$(selector).dialog("close");
			}
		});
	}

	function selectTemplate(documentId) {
		$("#template-form tr").removeClass("selected-row");
		$("#template-form #" + documentId).addClass("selected-row");
		$("#template-form #TemplateId").val(documentId);
	}

	function createDocument() {
		if ($("#template-form #TemplateId").val() === "")
			return;

		$("#template-form").block();

		var selector = "#template-form";
		var prog = kaskelot.sp.ui.formutils.getObject(selector);

		var method = "RenderPersonDocument";

		$.ajax({
			url: L_Menu_BaseUrl + "/_vti_bin/Kaskelot.SP.Resources/ClientDocumentService.svc/" + method,
			data: JSON.stringify(prog),
			type: "POST",
			processData: false,
			contentType: "application/json",
			dataType: "json",
			success: function (resp) {
				if (resp[method + "Result"].HasError) {
					kaskelot.sp.ui.formutils.showError(selector, resp[method + "Result"].ErrorMessage);
				}
				else {
					$("#file-link").attr("href", "../../" + resp[method + "Result"].Data);
					$("#file-link").show();
				}
				$("#template-form").unblock();
			},
			error: function (xhr) {
				kaskelot.sp.ui.formutils.showError(selector, xhr.responseText);
				$("#template-form").unblock();
			}
		});
	}

	return {
		init: init,
		getList: getList,
		selectTemplate: selectTemplate,
		createDocument: createDocument,
		showTemplates: showTemplates,
		showEmail: showEmail
	}
}();